<?php
/**
 * Created by PhpStorm.
 * User: t
 * Date: 2024/3/5
 * Time: 11:57
 */

namespace app\merchant\controller;


use app\admin\model\Role;
use app\admin\model\Staff;
use app\home\model\Sms;
use app\home\model\User;
use app\home\model\UserToken;
use app\services\jwt\JwtService;
use think\Request;
use think\Validate;

class Merchant
{

    public function userInfo(Request $request)
    {

        $roleModel = new Role();
        $roleInfo = $roleModel->where(['id'=>  $request->staff_account['role_id']])->find();
        if ($roleInfo){
            $request->staff_account['role_type'] = $roleInfo['type'];
        }else{
            $request->staff_account['role_type'] = 1;

        }
        return success('用户信息', $request->staff_account);
    }

    /**
     *   手机号登录/注册
     */
    public function login(Request $request)
    {
        $param = $request->param();
        $phone = $param['account'];
        if (empty($phone)) {
            return error('请填写手机号码或账号');
        }
        $StaffAccountModel = new Staff();
        $staffAccount = $StaffAccountModel->where('phone', $param['account'])
            ->whereOr('name', $param['account'])->find();
        if (!$staffAccount){
            return error('用户不存在');
        }
        if ($staffAccount['password'] != md5(md5($param['password']) . $staffAccount['salt'])) {
            return error('密码错误');
        }
        /* if (!isset($param['code']) || empty($param['code'])) {
             return error('请填写短信验证码');
         }
         $smsInfo = Sms::checkCode($param['phone'], $param['code'], '2');
         if ($smsInfo['code'] != 1000) {
             return error($smsInfo['msg']);
         }*/
        try {
            if ($staffAccount) {
                if ($staffAccount['status'] != 1) {
                    return error("账号未启用,请联系管理员", [], '204');
                }
                $userDate['last_login_ip'] = request()->ip();
                $userDate['last_login_time'] = time();
                $StaffAccountModel->where(['id' => $staffAccount['id']])->update($userDate);
                $id = $staffAccount['id'];
            } else {
                $userDate['create_time'] = time();
                $userDate['name'] = time();
                $userDate['phone'] = $param['phone'];
                $userDate['avatar'] = 'www.baidu.com';
                $StaffAccountModel->save($userDate);
                $id = $StaffAccountModel->getLastInsID();
            }
            $jwt = new JwtService();
            //根据用户id生成token
            if (isset($param['store_id']) && !empty($param['store_id'])) {
                $storeId = $param['store_id'];
            } else {
                $storeId = 0;
            }
            if (isset($param['role_id']) && !empty($param['role_id'])) {
                $roleId = $param['role_id'];
            } else {
                $roleId = 0;
            }


            $token = $jwt->getMerchantToken($id, $roleId, $storeId, 30);  //获取token
            $tokenConfig = ['uid' => $id, 'token' => $token, 'create_time' => time(),
                'effective_time' => time() + 60 * 60 * 24 * 30, 'login_ip' => $request->ip(), 'type' => 2];  //token配置信息  //token配置信息
            $tokenModel = new UserToken();
            $staffAccount = $StaffAccountModel->where(['phone' => $staffAccount['phone']])->find();
            $roleModel = new Role();
            $roleInfo = $roleModel->where(['id'=> $roleId])->find();
            if ($roleInfo){
                $staffAccount['role_type'] = $roleInfo['type'];
            }else{
                $staffAccount['role_type'] = 1;

            }
            $staffAccount['role_id'] = $roleId;
            $staffAccount['store_id'] = $storeId;
            $tokenModel->insert($tokenConfig);  //更新token
            $staffAccount['token'] = $token;
            return success('登录成功', $staffAccount);
        } catch (\Exception $e) {
            return error($e->getMessage() . $e->getLine());
        }
    }

    /**
     * 发送短信
     */
    public function smsCode(Request $request)
    {
        /*   try {*/
        $smsModel = new Sms();
        $expire = 60;
        $maxSendNums = 5;
        $param = $request->param();
        if (!$param['phone'] || !(new Validate())->rule($param['phone'], '^1\d{10}$')) {
            return error('手机号不正确');
        }
        $lastSend = $smsModel->where(['phone' => $param['phone'], 'type' => '2'])->find();
        if ($lastSend && time() - strtotime($lastSend['create_time']) < $expire) {
            return error('发送频繁');
        }
        $ipSendTotal = $smsModel->where(['ip' => request()->ip()])->whereTime('create_time', '-1 hours')->count();
        if ($ipSendTotal >= $maxSendNums) {
            return error('发送频繁');
        }
        $code = mt_rand(1000, 9999);
        $ip = request()->ip();
        $smsModel->startTrans();
        $sms = $smsModel->save(['type' => '2', 'phone' => $param['phone'], 'code' => $code, 'ip' => $ip]);
        if ($sms === false) {
            $smsModel->rollback();
            return error('发送失败');
        }
        /**
         *  三方接口
         */
        if (true) {
            $smsModel->commit();
            return success('发送成功');
        } else {
            $smsModel->rollback();
        }
        /*   } catch(Exception $e) {
               throw new Exception($e->getMessage());
           }*/
    }

    public function updateAccount(Request $request){
        $param = $request->param();

        if(isset($param['password'])&& !empty($param['password']) ){
            $salt  = createNonceStr(4);
            $data['password'] = md5(md5($param['password']) . $salt) ;
            $data['salt'] =$salt;
        }
        if(isset($param['phone'])&& !empty($param['phone']) ){

            $data['phone'] =$param['phone'];
        }
        if(isset($param['name'])&& !empty($param['name']) ){

            $data['name'] =$param['name'];
        }
        if(isset($param['real_name'])&& !empty($param['real_name']) ){

            $data['real_name'] =$param['real_name'];
        }

        $staffModel = new \app\admin\model\Staff();
        $staffModel->where(['id' => $request->staff_account['id']])->update($data);
        return success('操作成功');

    }


}
